package com.example.finance_manager.pages;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import com.example.finance_manager.GLOBAL;
import com.example.finance_manager.R;
import com.example.finance_manager.dao.UserDao;
import com.example.finance_manager.models.User;

import java.util.List;

public class LoginActivity extends AppCompatActivity {
    private Button btnLogin;
    private EditText etNumber;
    private EditText etPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();
        initListener();

        etNumber.setText("1");
        etPassword.setText("1");
    }

    private void initView() {
        btnLogin = findViewById(R.id.btn_login_login);
        etNumber = findViewById(R.id.et_login_number);
        etPassword = findViewById(R.id.et_login_password);
    }

    private void initListener() {
        btnLogin.setOnClickListener(view -> {
            login();
        });
    }

    private void login() {
        UserDao userDao = new UserDao(LoginActivity.this);
        String username = etNumber.getText().toString();
        String password = etPassword.getText().toString();
        List<User> users = userDao.findByUsername(username);
        if (users.isEmpty()) {
            userDao.add(new User(username, password));
            showAlertDialog("提示", "用户注册成功");
        } else {
            String relPassword = users.get(0).getPassword();
            if (relPassword.equals(password)) {
                showAlertDialog("提示", "登陆成功！");
                GLOBAL.username = username;
                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                startActivity(intent);
            } else {
                showAlertDialog("提示", "帐号或密码错误！");
                etPassword.setText("");
            }
        }
    }

    private void showAlertDialog(String title, String msg) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(msg)
                .setPositiveButton("确定", null)
                .show();
    }
}